from py_sql import mysql


class ClassOrder:
    def __init__(self, start_date, end_date):

        """
        :param start_date: 课程分页显示用的日期,格式是：20180101
        :param end_date: 课程分页显示用日期，格式是：20180101
        """
        self.startdate = start_date
        self.enddate = end_date
        self.mysql_cur = mysql()
        self.class_count = self.class_count()

    def class_order_time(self, stu_id, class_id, start_time: int):
        # 问题：当需要两条查询语句的结果同时进行匹配的时候，是通过sql直接查询
        # 还是分成两条分别查询，然后在代码里判断
        sql_list = [self.class_is_order(stu_id)]
        for sql in range(len(sql_list)):
            sqlr = self.mysql_cur.operation(sql_list[sql])
            if sqlr:
                if sql == 0:
                    return sqlr  # 在这个时间端已经有其他的课程了,发现了就返回这个值
        else:
            insert_order_time = 'insert into class_order(stu_id, class_id, start_time) ' \
                                'values("%s","%s", %d)' % (stu_id, class_id, start_time)
            try:
                self.mysql_cur.operation(insert_order_time)  # 符合上面两个条件,将预约信息写入到数据库

            except Exception as e:
                print('学生%s 预约时间为: %d-%d 的课程: %s 失败, 错误原因: %s '
                      % (stu_id, start_time, start_time + 1, class_id, e))
                return 500
            else:
                print('学生%s 预约时间为: %d-%d 的课程: %s 成功')
                return 10000

    def choice_class(self):
        pass

    def class_order_info(self, start_time, end_time):
        get_class_info = 'select class_id, class_name, start_time from class_order ' \
                         'where date between %s and %s"' % (start_time, end_time)
        self.mysql_cur.operation(get_class_info)

    def class_count(self):
        get_class_count = 'select count(class_date) from class_order ' \
                          'where class_date between %s and %s group by class_date' \
                          % (self.startdate, self.enddate)
        sqlr = self.mysql_cur.operation(get_class_count)

        return sqlr[0][0]

    def class_is_order(self, stu_id):
        stu_is_time = 'select class_name start_time from class_order ' \
                      'where stu_id="%s", start_time=%s group by start_time'  \
                      % (stu_id, self.startdate)
        sqlr = self.mysql_cur.operation(stu_is_time)
        return sqlr
